package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.config.ConfigFile;
import com.fwtai.poi.ToolExcel;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import com.fwtai.web.FinancialDetailsDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 财务明细业务层
 * @作者 李宇鹏
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2023-05-30 16:57:22
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class FinancialDetailsService{

  private final FinancialDetailsDao financialDetailsDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  @Value("${upload_dir_window}")
  private String dir_window;

  @Value("${upload_dir_linux}")
  private String dir_linux;

  public FinancialDetailsService(final FinancialDetailsDao financialDetailsDao,final ThreadPoolTaskExecutor taskExecutor){
    this.financialDetailsDao = financialDetailsDao;
    this.taskExecutor = taskExecutor;
  }

  public String queryById(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.queryJson(financialDetailsDao.queryById(kid));
    },taskExecutor).join();
  }

  public String getType(final String type){
    switch (type){
      case "1":
        return "(省分公司)";
      case "2":
        return "(市分公司)";
      case "3":
        return "(区代理)";
      case "4":
        return "(直营门店)";
      case "5":
        return "(推荐人)";
      case "6":
        return "(事业部)";
      default:
        return "";
    }
  }

  String handlerType(final int type){
    switch (type){
      case 1:
        return "消费者购买";
      case 2:
        return "直营店采购";
      case 3:
        return "区代理采购";
      default:
        return "";
    }
  }

  //导出
  public void getDataExport(final HttpServletRequest request,final HttpServletResponse response){
    CompletableFuture.runAsync(()->{
      final PageFormData formData = new PageFormData(request);
      formData.remove(ConfigFile.ACCESS_TOKEN);
      formData.remove(ConfigFile.REFRESH_TOKEN);
      formData.put("export",1);
      final CompletableFuture<List<Map<String,Object>>> listData = CompletableFuture.supplyAsync(() -> financialDetailsDao.getListData(formData),taskExecutor);
      final List<Map<String,Object>> list = listData.join();
      handler(list);
      final int size = list.size();
      if(size == 0){
        ToolClient.responseJson(ToolClient.createTitleMsg("暂无数据可供下载"),response);
        return;
      }
      if(size > 51200){//视情况是否需要限制导出条数
        ToolClient.responseJson(ToolClient.createTitleMsg("导出不得超过51200条"),response);
        return;
      }
      for(int x = list.size() - 1; x >= 0; x--){
        final Map<String,Object> map = list.get(x);
        final HashMap<String,Object> details = (HashMap<String,Object>)map.get("details");
        final String contractName = (String) details.get("contract_name");//有可能是多件商品
        final String total = (String) details.get("total");
        final String item_fee = (String) details.get("item_fee");
        final String[] names = contractName.split(",");
        final String[] totals = total.split(",");
        final String[] item_fees = item_fee.split(",");
        //订单商品信息
        final StringBuilder builderOrder = new StringBuilder();
        for(int a = names.length - 1; a >= 0; a--){
          final String _totals = totals[a];
          final String _item_fees = item_fees[a];
          if(builderOrder.length() > 0){
            builderOrder.append("，");
          }
          builderOrder.append(names[a]);
          builderOrder.append(" * ");
          builderOrder.append(_totals);
          builderOrder.append(" 单价：￥ ");
          builderOrder.append(_item_fees);
        }
        final String split = "W_w_xin_Suo_Fa_Com";
        //订单分成信息
        final StringBuilder builder = new StringBuilder();
        final String realNames = (String)details.get("realName");

        if(realNames != null && realNames.length() > 0){
          final String types = (String)details.get("type");
          final String scores = (String)details.get("score");
          final String userName = (String)details.get("user_name");

          final String[] arrName = realNames.split(split);
          final String[] _types = types != null ? types.split(",") : new String[]{};
          final String[] _scores = scores.split(",");
          final String[] _userName = userName.split(",");

          for(int b = arrName.length - 1; b >= 0; b--){
            try {
              if(builder.length() > 0){
                builder.append("，");
              }
              builder.append(getType(_types[b]));
            } catch (final Exception ignored) {}
            builder.append("账号：");
            builder.append(_userName[b]);
            builder.append(" ");
            builder.append(arrName[b]);
            builder.append(" 分成：￥ ");
            builder.append(_scores[b]);
          }
        }
        map.remove("details");
        final Long type = (Long)map.get("orderType");
        map.put("orderType",type == 1 ? "微信订单" : "积分订单");
        final Integer buyerType = (Integer)map.get("buyer_type");
        map.put("buyer_type",buyerType == null ? "" : handlerType(buyerType));
        final Long status = (Long)map.get("status");
        map.put("status",status == 1 ? "已支付" : "未支付");
        map.put("add_date",ToolString.timestampToDateTime((Long) map.get("add_date")));
        final Long pay_date = (Long)map.get("pay_date");
        map.put("pay_date",pay_date != null ? ToolString.timestampToDateTime(pay_date) : "");
        map.put("builderOrder",builderOrder);
        map.put("builder",builder);
      }
      final ArrayList<String> fields = new ArrayList<>(17);
      fields.add("buyer");
      fields.add("buyerName");
      fields.add("buyerNick");
      fields.add("payee");
      fields.add("payeeName");
      fields.add("payeeNick");
      fields.add("orderType");
      fields.add("buyer_type");
      fields.add("transaction_id");
      fields.add("out_trade_no");
      fields.add("total_fee");
      fields.add("builderOrder");
      fields.add("builder");
      fields.add("status");
      fields.add("add_date");
      fields.add("pay_date");
      fields.add("body");

      final ArrayList<String> titles = new ArrayList<>(fields.size());
      titles.add("购买人账号");
      titles.add("购买人姓名");
      titles.add("购买人昵称");
      titles.add("收款人账号");
      titles.add("收款人姓名");
      titles.add("收款人昵称");
      titles.add("订单类型");
      titles.add("购买类型");
      titles.add("交易单号");
      titles.add("商户单号");
      titles.add("订单金额");
      titles.add("订单商品信息");
      titles.add("订单分成信息");
      titles.add("支付状态");
      titles.add("下单时间");
      titles.add("付款时间");
      titles.add("订单描述");
      try{
        ToolExcel.exportExcel(list,fields,titles,"订单明细","订单明细"+new ToolString().getDateTime()+".xlsx",response);
      }catch(final Exception e){
        ToolClient.responseJson(ToolClient.createTitleMsg("服务出现错误"),response);
      }
    },taskExecutor).join();
  }

  public void handler(final List<Map<String,Object>> list){
    final ArrayList<Long> listParams = new ArrayList<>(list.size());
    for(int i = list.size() - 1; i >= 0; i--){
      listParams.add((Long) list.get(i).get("kid"));
    }
    if(listParams.size() > 0){
      final List<HashMap<String,Object>> details = financialDetailsDao.getOrderDetails(listParams);
      for(int x = list.size() - 1; x >= 0; x--){
        final Map<String,Object> map = list.get(x);
        final Long out_trade_no = (Long) map.get("out_trade_no");
        for(int y = details.size() - 1; y >= 0; y--){
          final HashMap<String,Object> hashMap = details.get(y);
          final Long orderId = (Long) hashMap.get("out_trade_no");
          if(out_trade_no.equals(orderId)){
            map.put("details",hashMap);
            break;
          }
        }
      }
    }
  }

  public String listData(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      try{
        final PageFormData formData = new PageFormData(request);
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        ToolString.handlerAreaData(formData,null);
        final CompletableFuture<List<Map<String,Object>>> listData = CompletableFuture.supplyAsync(() -> financialDetailsDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> financialDetailsDao.getListTotal(formData),taskExecutor);
        final CompletableFuture<List<HashMap<String,Object>>> listMoneySum = CompletableFuture.supplyAsync(() -> financialDetailsDao.getListMoneySum(formData),taskExecutor);
        CompletableFuture.allOf(listData,listTotal,listMoneySum).join();//若出错取消注释即可
        final List<Map<String,Object>> list = listData.join();
        handler(list);
        final Integer total = listTotal.join();
        final List<HashMap<String,Object>> listMoney = listMoneySum.join();
        HashMap<String,Object> map = new HashMap<>();
        for (HashMap<String, Object> item : listMoney) {
          final int status = Integer.parseInt(String.valueOf(item.get("status")));
          final BigDecimal totalMoney = (BigDecimal) item.get("total");
          if(status == 0){
            map.put("orderUnpaidMoney", totalMoney);
          }else if(status == 1){
            map.put("orderPaidMoney", totalMoney);
          }else if(status == 2){
            map.put("orderMoney", totalMoney);
          }
        }
        return ToolClient.dataTableOK(list,total,map);
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }
}